package gk.example.activity;

import gk.example.App;
import gk.example.BaseActivity;
import gk.example.adapter.AttenderListAdapter;
import gk.example.bean.DateInfo;
import gk.example.bean.User;
import gk.example.util.ErrorCodeUtil;
import gk.example.util.ImageLoadUtil;
import gk.example.util.T;
import gk.example.view.ProgressDialog;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

import com.example.gkdate.R;

import de.hdodenhof.circleimageview.CircleImageView;

public class AttendActivity extends BaseActivity implements OnClickListener {
	private ImageButton mBtnBack;
	private TextView mTvTitle;
	private CircleImageView mImageUserHead;
	private TextView mTvAttentNickName;
	private TextView mTvAttentDetail;
	private TextView mTvAttentTime;
	private TextView mTvAttendDate;
	private TextView mTvAttentPlace;
	private TextView mTvAttentContact;
	private TextView mTvAttentAnnounceTime;
	private TextView mTvDatePeople;
	private ImageView mImageSex;
	private Button mBtnAttent;
	private Button mBtnStart;
	private TextView mTvAttendDateStatus;
	private ProgressDialog mProgressDialogEnter;
	private ProgressDialog mProgressDialogAttend;
	private RelativeLayout mRelativeLayout;
	private LinearLayout mLinearLayout;
	private Boolean isFirst;
	private ListView mLvAttender;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initView() {
		setContentView(R.layout.activity_attend);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mBtnAttent = (Button) findViewById(R.id.btn_attend);
		mBtnStart = (Button) findViewById(R.id.btn_start_date);
		mTvTitle = (TextView) findViewById(R.id.tv_top_title);
		mImageUserHead = (CircleImageView) findViewById(R.id.iv_attend_head);
		mTvAttentNickName = (TextView) findViewById(R.id.tv_attend_nick_name);
		mTvAttendDate = (TextView) findViewById(R.id.tv_attend_date);
		mTvAttentTime = (TextView) findViewById(R.id.tv_attend_time);
		mTvAttentPlace = (TextView) findViewById(R.id.tv_attend_place);
		mTvAttentContact = (TextView) findViewById(R.id.tv_attend_contact);
		mTvAttentDetail = (TextView) findViewById(R.id.tv_attend_detail);
		mTvAttentAnnounceTime = (TextView) findViewById(R.id.tv_attend_announce_time);
		mImageSex = (ImageView) findViewById(R.id.iv_attend_sex);
		mTvAttendDateStatus = (TextView) findViewById(R.id.tv_attend_status);
		mTvDatePeople = (TextView) findViewById(R.id.tv_attend_people);
		mProgressDialogEnter = new ProgressDialog();
		mProgressDialogAttend = new ProgressDialog();
		mRelativeLayout = (RelativeLayout) findViewById(R.id.rellay_attend_info);
		mLinearLayout = (LinearLayout) findViewById(R.id.linlay_attend_bottom);
		mLvAttender = (ListView) findViewById(R.id.lv_attender);
	}

	private static final int DATESTATUS_DONE = 0;
	private static final int DATESTATUS_GOING = 1;
	private static final int DATESTATUS_READY = 2;

	@Override
	protected void initEvent() {
		mImageUserHead.setOnClickListener(this);
		setAttender();
		getAnnouncer();
		mProgressDialogEnter.show(getSupportFragmentManager(), "LOADING");
		mProgressDialogAttend.setMsg("正在处理");
		mImageUserHead.setImageResource(R.drawable.default_round_head);
		mTvTitle.setText("详情");
		mBtnBack.setOnClickListener(this);
		mBtnAttent.setOnClickListener(this);
		mBtnStart.setOnClickListener(this);
		isFirst = true;
		isAttend();
	}

	private void setInfo() {
		if (App.Announcer.getNickName() != null) {
			mTvAttentNickName.setText(App.Announcer.getNickName());
		}
		if (App.DateInfo.getDateDetail() != null) {
			mTvAttentDetail.setText(App.DateInfo.getDateDetail());
		}
		if (App.DateInfo.getDateDate() != null
				&& App.DateInfo.getDateTime() != null) {
			mTvAttendDate.setText(App.DateInfo.getDateDate());
			mTvAttentTime.setText(App.DateInfo.getDateTime());
		}
		if (App.DateInfo.getDatePlace() != null) {
			mTvAttentPlace.setText(App.DateInfo.getDatePlace());
		}
		if (App.Announcer.getContact() != null) {
			mTvAttentContact.setText(App.Announcer.getContact());
		}
		if (App.DateInfo.getCreatedAt() != null) {
			mTvAttentAnnounceTime.setText(App.DateInfo.getCreatedAt());
		}
		if (App.DateInfo.getDatePeople() != null
				&& App.DateInfo.getDateCurrentPeople() != null) {
			mTvDatePeople.setText("人数:" + App.DateInfo.getDateCurrentPeople()
					+ "/" + App.DateInfo.getDatePeople());
		}
		if (App.Announcer.getSex() != null) {
			if (App.Announcer.getSex().equals("男")) {
				mImageSex.setBackgroundResource(R.drawable.ic_sex_male);
			} else {
				mImageSex.setBackgroundResource(R.drawable.ic_sex_female);
			}
		}
		if (App.Announcer.getUserHead() != null) {
			ImageLoadUtil.getInstance().setImageBackground(this, false,
					mImageUserHead,
					App.Announcer.getUserHead().getFileUrl(this), null, 38, 38);
		}
		int tempStr = App.DateInfo.getDateStatus();
		if (tempStr == DATESTATUS_DONE) {
			mTvAttendDateStatus.setText("已结束");
			mTvAttendDateStatus.setTextColor(getResources().getColor(
					R.color.date_color_done));
		} else if (tempStr == DATESTATUS_GOING) {
			mTvAttendDateStatus.setText("进行中");
			mTvAttendDateStatus.setTextColor(getResources().getColor(
					R.color.date_color_going));
		} else if (tempStr == DATESTATUS_READY) {
			mTvAttendDateStatus.setText("准备中");
			mTvAttendDateStatus.setTextColor(getResources().getColor(
					R.color.date_color_ready));
		} else {

		}
	}

	/**
	 * 
	 * 描述： 参与约会
	 * 
	 * @return void
	 */
	private void attendDate() {
		mProgressDialogAttend.show(getSupportFragmentManager(), "ATTEND");
		DateInfo dateInfo = App.DateInfo;
		if (mBtnAttent.getText().toString().equals("取消参与")
				&& !(App.Announcer.getObjectId().equals(App.BmobUser
						.getObjectId()))) {
			dateInfo.setDateCurrentPeople((Integer.parseInt(App.DateInfo
					.getDateCurrentPeople()) - 1) + "");
			BmobRelation attender = new BmobRelation();
			attender.remove(App.BmobUser);
			dateInfo.setAttender(attender);

		} else if (mBtnAttent.getText().toString().equals("参与")) {
			dateInfo.setDateCurrentPeople((Integer.parseInt(App.DateInfo
					.getDateCurrentPeople()) + 1) + "");
			BmobRelation attender = new BmobRelation();
			attender.add(App.BmobUser);
			dateInfo.setAttender(attender);
		} else if (mBtnAttent.getText().toString().equals("结束约会")) {
			dateInfo.setDateStatus(0);// 0代表结束约会
		}
		dateInfo.update(this, new UpdateListener() {
			@Override
			public void onSuccess() {
				addDateToUser();
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "操作失败");
				mProgressDialogAttend.dismiss();
			}
		});

	}

	/**
	 * 
	 * 描述： 添加约会信息到用户
	 * 
	 * @return void
	 */
	private void addDateToUser() {
		BmobRelation dateInfo = new BmobRelation();
		if (mBtnAttent.getText().toString().equals("取消参与")
				&& !(App.Announcer.getObjectId().equals(App.BmobUser
						.getObjectId()))) {
			dateInfo.remove(App.DateInfo);
		} else if (mBtnAttent.getText().toString().equals("参与")) {
			dateInfo.add(App.DateInfo);
		}
		App.BmobUser.setDateRecord(dateInfo);
		App.BmobUser.update(this, new UpdateListener() {

			@Override
			public void onSuccess() {
				if (mBtnAttent.getText().toString().equals("取消参与")
						&& !(App.Announcer.getObjectId().equals(App.BmobUser
								.getObjectId()))) {
					T.show(AttendActivity.this, "取消成功", Toast.LENGTH_SHORT);
					startActivity(new Intent(AttendActivity.this,
							MainActivity.class));
				} else if (mBtnAttent.getText().toString().equals("参与")) {
					T.show(AttendActivity.this, "参与成功", Toast.LENGTH_SHORT);
					startActivity(new Intent(AttendActivity.this,
							DateRecordActivitiy.class));
				} else if (mBtnAttent.getText().toString().equals("结束约会")) {
					T.show(AttendActivity.this, "结束成功", Toast.LENGTH_SHORT);
					startActivity(new Intent(AttendActivity.this,
							MainActivity.class));
				}
				mProgressDialogAttend.dismiss();
				finish();
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				if (mBtnAttent.getText().toString().equals("取消参与")
						&& !App.Announcer.getObjectId().equals(
								App.BmobUser.getObjectId())) {
					ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "取消失败");
				} else if (mBtnAttent.getText().toString().equals("参与")) {
					ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "参与失败");
				} else if (mBtnAttent.getText().toString().equals("结束")) {
					ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "结束失败");
				}
				mProgressDialogAttend.dismiss();
			}
		});

	}

	private Boolean isAttend;

	/**
	 * 
	 * 描述：判断是否已经参与
	 * 
	 * @return void
	 */
	private void isAttend() {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereRelatedTo("Attender", new BmobPointer(App.DateInfo));
		query.findObjects(this, new FindListener<User>() {

			@Override
			public void onSuccess(List<User> arg0) {
				if (arg0.size() != 0) {
					App.Attender = arg0;
					for (int i = 0; i < arg0.size(); i++) {
						if (App.Announcer.getObjectId().equals(
								App.BmobUser.getObjectId())) {
							mBtnAttent.setText("结束约会");
							isAttend = true;
							mBtnAttent
									.setBackgroundResource(R.drawable.selector_btn_attend_cancel);
							mBtnStart.setVisibility(View.VISIBLE);
						} else if (arg0.get(i).getObjectId()
								.equals(App.BmobUser.getObjectId())) {
							mBtnAttent.setText("取消参与");
							isAttend = true;
						} else {
							isAttend = false;
						}
					}

				}
				attendDateJudge();
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "加载失败");
				mProgressDialogEnter.dismiss();
			}
		});

	}

	/**
	 * 
	 * 描述：判断是否满人
	 * 
	 * @return void
	 */
	private void attendDateJudge() {
		if (mBtnAttent.getText().toString().equals("联系队友")) {
			startActivity(new Intent(AttendActivity.this, ContactActivity.class));
			return;
		}
		BmobQuery<DateInfo> query = new BmobQuery<DateInfo>();
		query.addWhereMatches("objectId", App.DateInfo.getObjectId());
		query.findObjects(this, new FindListener<DateInfo>() {

			@Override
			public void onSuccess(List<DateInfo> arg0) {
				mLinearLayout.setVisibility(View.VISIBLE);
				mRelativeLayout.setVisibility(View.VISIBLE);
				mLvAttender.setVisibility(View.VISIBLE);
				App.DateInfo.setDateCurrentPeople(arg0.get(0)
						.getDateCurrentPeople());
				if (App.DateInfo.getDatePeople() != null
						&& App.DateInfo.getDateCurrentPeople() != null) {
					mTvDatePeople.setText("人数:"
							+ App.DateInfo.getDateCurrentPeople() + "/"
							+ App.DateInfo.getDatePeople());
				}
				mProgressDialogEnter.dismiss();
				if (arg0.get(0).getDateStatus() == 0) {
					mBtnAttent.setText("当前约会已结束");
					mBtnAttent.setBackgroundColor(R.color.activity_background);
					mBtnAttent.setClickable(false);
					mBtnStart.setVisibility(View.GONE);
					return;
				} else if (arg0.get(0).getDateStatus() == 1) {
					for (int i = 0; i < App.Attender.size(); i++) {
						if (App.BmobUser.getObjectId().equals(
								App.Attender.get(i).getObjectId())) {
							mBtnAttent.setText("联系队友");
							mBtnStart.setVisibility(View.GONE);
							mBtnAttent
									.setBackgroundResource(R.drawable.selector_btn_attend_cancel);
							return;
						}
					}
					mBtnAttent.setText("当前约会已在进行中");
					mBtnAttent.setBackgroundColor(R.color.activity_background);
					mBtnAttent.setClickable(false);
					mBtnStart.setVisibility(View.GONE);

					return;
				}

				if (arg0.size() != 0) {
					if (Integer.parseInt(arg0.get(0).getDatePeople()) == Integer
							.parseInt(arg0.get(0).getDateCurrentPeople())
							&& isAttend) {
						mBtnAttent.setText("人数已满");
						mBtnAttent
								.setBackgroundColor(R.color.activity_background);
						mBtnAttent.setClickable(false);
					} else if (!isFirst) {
						attendDate();
					}
				}

			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "加载失败");
				mProgressDialogEnter.dismiss();
			}
		});
	}

	/**
	 * 
	 * 描述： 设置参与者
	 * 
	 * @return void
	 */
	private void setAttender() {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereRelatedTo("Attender", new BmobPointer(App.DateInfo));
		query.findObjects(this, new FindListener<User>() {
			@Override
			public void onSuccess(final List<User> arg0) {
				mLvAttender.setAdapter(new AttenderListAdapter(
						AttendActivity.this, arg0));
				mLvAttender.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						setOnAttenderClickListener(arg0.get(position)
								.getObjectId());
					}
				});
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "加载失败");
			}
		});
	}

	Intent intent;

	private void setOnAttenderClickListener(String UserID) {
		intent = new Intent(AttendActivity.this, OtherInfoActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("userid", UserID);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	private void getAnnouncer() {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereMatches("objectId", App.Announcer.getObjectId());
		query.findObjects(this, new FindListener<User>() {

			@Override
			public void onSuccess(List<User> arg0) {
				App.Announcer = arg0.get(0);
				BmobQuery<DateInfo> query = new BmobQuery<DateInfo>();
				query.addWhereMatches("objectId", App.DateInfo.getObjectId());
				query.findObjects(getApplicationContext(),
						new FindListener<DateInfo>() {

							@Override
							public void onSuccess(List<DateInfo> arg0) {
								App.DateInfo = arg0.get(0);
								setInfo();
							}

							@Override
							public void onError(int arg0, String arg1) {

							}
						});

			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "读取数据失败");
			}
		});
	}

	/**
	 * 
	 * 描述： 开始约会
	 * 
	 * @return void
	 */
	private void startDate() {
		BmobQuery<DateInfo> query = new BmobQuery<DateInfo>();
		query.addWhereMatches("objectId", App.DateInfo.getObjectId());
		query.findObjects(this, new FindListener<DateInfo>() {

			@Override
			public void onSuccess(List<DateInfo> arg0) {
				App.DateInfo = arg0.get(0);
				if (App.DateInfo.getDateCurrentPeople().equals("1")) {
					T.show(AttendActivity.this, "当前约会无人加入,无法开始",
							Toast.LENGTH_SHORT);
					return;
				}
				mProgressDialogAttend.show(getSupportFragmentManager(),
						"LOADING");
				App.DateInfo.setDateStatus(1);// 1代表进行中
				App.DateInfo.update(AttendActivity.this, new UpdateListener() {

					@Override
					public void onSuccess() {
						T.show(AttendActivity.this, "操作成功", Toast.LENGTH_SHORT);
						finish();
						startActivity(new Intent(AttendActivity.this,
								MainActivity.class));
						mProgressDialogAttend.dismiss();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						ErrorCodeUtil.Errorshow(AttendActivity.this, arg0,
								"参与失败");
						mProgressDialogAttend.dismiss();
					}
				});
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(AttendActivity.this, arg0, "参与失败");
				mProgressDialogAttend.dismiss();
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(AttendActivity.this, MainActivity.class));
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_back:
			startActivity(new Intent(AttendActivity.this, MainActivity.class));
			finish();
			break;
		case R.id.btn_attend:
			isFirst = false;
			attendDateJudge();
			break;
		case R.id.btn_start_date:
			startDate();
			break;
		case R.id.iv_attend_head:
			Intent intent = new Intent(this, OtherInfoActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("userid", App.Announcer.getObjectId());
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

}
